<?php
class SecurityContext {
	
	const RULE_ALLOW = 'allow';
	const RULE_DENY = 'deny';
	
	const DEFAULT_VISITOR_ROLE = 'guest';
	
	private static $instance = null;
	
	private $rules;
	private $defaults;
	private $roles;
	private $session;
	
	private function __construct() {
		$this->session = new Zend_Session_Namespace('security');
	}
	
	public function authenticate() {
		
	}
	
	public function authorize(Zend_Controller_Request_Http $request) {
		$visitor = &$this->session->visitor;
		
//		var_dump($visitor);
		
		if (empty($visitor)) {
			$visitor = $this->factoryVisitor();
		}
		
		if (!isset($this->rules[$request->getControllerName()])) {
//			echo "Controller not defined";
			return $this->getDefaultRule();
		}
		
		$cfg = $this->rules[$request->getControllerName()];
		
		if (!isset($cfg[$request->getActionName()])) {
//			echo "Action not defined";
			return $this->getDefaultRule();
		}
		
		$cfg = $cfg[$request->getActionName()];
		
		if (isset($cfg['allow'])) {
			foreach ($this->session->visitor['roles'] as $role) {
				if (in_array($role, $cfg['allow'])) {
					return true;
				} 
			}
		}
		
		if (isset($cfg['deny'])) {
			foreach ($this->session->visitor['roles'] as $role) {
				if (in_array($role, $cfg['deny'])) {
					return false;
				} 
			}
		}
		
		return $this->getDefaultRule();
	}
	
	public function hasRole($role) {
		return in_array($role, $this->roles);
	}
	
	public function setup($config) {
		$this->rules = $config['rules'];
		$this->defaults = $config['defaults'];
		$this->roles = $config['roles'];
	}
	
	public function getAuthenticationUrl() {
		return $this->defaults['auth_url'];
	}
	
	/**
	 * Return the hash of a string. Used for password encoding.
	 * @param string $string
	 * @return string
	 */
	public function getSecurityHash($string) {
		return md5($string);
	}
	
	/**
	 * Return the default access rule
	 */
	private function getDefaultRule() {
		return ($this->defaults['rule'] == self::RULE_ALLOW) ? true : false;
	}
	
	private function factoryVisitor() {
		$visitor = array(
			'roles' => array($this->defaults['role'])
		);
		
//		echo "Factory";
//		var_dump($visitor);
		
		$this->session->visitor = $visitor;
		return $visitor;
	}
	
	/**
	 * @return SecurityContext 
	 */
	public static function instance() {
		if (self::$instance == null) {
			self::$instance = new SecurityContext();
		}
		
		return self::$instance;
	}
	
}